// pages/index/shopInfo.js
var app = getApp();
var regionData = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    loading: 0,
    disabled: 0,
    areaRegionCode:[],
    bankRegionCode:[],
    type: 2,
    order_sn: "",
    userInfo: {},
    bankRegion: [],
    bankRegionCode: [],
    regionIndex: [0, 0],
    user_tag: 0,
    bankList: [],
    MerchantType:"02",
    uploadlist: [],
    provinceArray: [],
    regionArray: [[], []],
    regionArray2: [[], [], []],
    regionIndex2: [0, 0, 0],
    industryList: [],
    industryIndex: [0],
    feeValueList: [],
    feeValueIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type) {
      // this.data.type = options.type;
      this.setData({ type: options.type})
    }


    app.getUserInfo((info) => {
      this.data.userInfo = info
      this.getFeeValueList();
    })

    this.getBank();
    this.getBankArea();
    this.getBankSubbranch();
    this.getIndustryList();

  },
  getFeeValueList: function () {
    var that = this;
    app.api("apiv2/mch_my_bank/getFeeList", {
      pid: this.data.userInfo.user_id
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.data.rawFeeValueList = res.data;
      var list = [];
      for (var i in res.data) {
        list.push(res.data[i].text);
      }
      // console.log(list);
      that.setData({ feeValueList: list });
    });
  },
  bindfeeValueChange: function (e) {
    console.log(e);
    var index = e.detail.value;
    var data = this.data.rawFeeValueList[index];
    this.setData({ feeValueText: data.text, feeValue: data.value });
  },
  getIndustryList: function () {
     this.data.rawIndustryList = [{
      industryId: '4015063000020189',
      industryName: '物业缴费'
    }, {
      industryId: '2015050700000000',
      industryName: '美食'
    }, {
      industryId: '2015091000052157',
      industryName: '超市便利店'
    }, {
      industryId: '2015062600004525',
      industryName: '休闲娱乐'
    }, {
      industryId: '2015062600002758',
      industryName: '购物'
    }, {
      industryId: '2016062900190124',
      industryName: '爱车'
    }, {
      industryId: '2015063000020189',
      industryName: '生活服务'
    }, {
      industryId: '2016062900190296',
      industryName: '医疗健康'
    }, {
      industryId: '2016042200000148',
      industryName: '教育培训'
    }, {
      industryId: '2015080600000001',
      industryName: '航旅'
    }, {
      industryId: '2016062900190337',
      industryName: '专业销售/批发'
    }, {
      industryId: '2016062900190371',
      industryName: '政府/社会组织'
    }];
    var industryList =[];
    for (var i in this.data.rawIndustryList){
      industryList.push(this.data.rawIndustryList[i].industryName);
    }
    this.setData({
      industryList: industryList
    })
  },
  
  bindIndustryChange: function (e) {
    
    var value = e.detail.value;
    this.data.industryId = this.data.rawIndustryList[value].industryId;
    this.data.industryName = this.data.rawIndustryList[value].industryName;
    this.setData({ industryName: this.data.industryName });
  },

  // 选择银行
  getBank: function () {
    var that = this;
    app.api("apiv2/bank/getBank", {
      cacheKey:'bankGetBank',
    }, function (res) {

      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.data.rawBankList = res.data;
      var bankList = [];
      for (var i in res.data) {
        bankList.push(res.data[i].bankName);
      }
      that.setData({ bankList: bankList });
    });
  },
  bindBankIdChange: function (e) {
    var index = e.detail.value;
    var bankId = this.data.rawBankList[index].bankId;
    var bankName = this.data.rawBankList[index].bankName;
    this.setData({ bankId: bankId, bankName: bankName });
    this.getBankSubbranch();

  },
  getBankSubbranch: function () {
    var that = this;
    var data = {};
    if (!(that.data.bankId && that.data.bankRegion.length == 2)) {
      return;
    }
    this.setData({
      contactLineName: "",
      contactLine:"",
      contactLineIndex: 0,
      rawBankSubbranchList:[],
      bankSubbranchList:[]

    });
    data.bankId = that.data.bankId;
    data.city_name = that.data.bankRegion[1];
    app.api("apiv2/bank/getBankSubbranch", data, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.data.rawBankSubbranchList = res.data;
      var bankSubbranchList = [];
      for (var i in res.data) {
        bankSubbranchList.push(res.data[i].sub_bankName);
      }
      that.setData({ bankSubbranchList: bankSubbranchList });
    });
  },
  bindbankSubbranchChange: function (e) {
    var index = e.detail.value;
    var data = this.data.rawBankSubbranchList[index];
    //  var contactLineName = data.sub_bankName;
    this.setData({
      contactLineName: data.sub_bankName,
      contactLine: data.contactLine,
      contactLineIndex: index
    });


  },
  // 省市区开户地联动
  getBankArea: function (pid = 1, type = 1) {
    var that = this;
    var cacheKey = "getArea_" + pid + "_" + type;
    app.api("api/index/render", {
      action: "getChilds",
      pid: pid,
      method: "post",
      cacheKey: cacheKey,
    }, function (res) {
      if (!res.success) {
        app.alert(res.error);
        return;
      }

      // var regionArray = [[],[]];
      regionData[pid] = res.data;
      if (pid == 1) {
        that.data.provinceArray = res.data;
        for (var i in res.data) {
          that.data.regionArray[0].push(res.data[i].areaName);
          that.data.regionArray2[0].push(res.data[i].areaName);
          // console.log(that.data.regionArray2[0]);
          that.getBankArea(res.data[i].areaCode);
        }
        that.setData({ regionArray: that.data.regionArray, regionArray2: that.data.regionArray2});
      } else if (pid == '110000') {
        if (that.data.regionArray[1].length == 0) {
          for (var i in res.data) {
            that.data.regionArray[1].push(res.data[i].areaName);
            that.data.regionArray2[1].push(res.data[i].areaName);
            if (res.data[i].areaCode == "110100") {
              that.getBankArea(res.data[i].areaCode, 3);
            }
          }
        }
        that.setData({ regionArray: that.data.regionArray, regionArray2: that.data.regionArray2 });
      } else if (type == 3) {
        that.data.regionArray2[2] = [];
        for (var i in res.data) {
          that.data.regionArray2[2].push(res.data[i].areaName);
          that.setData({ regionArray2: that.data.regionArray2 });
        }
      }
    });
  },
  // 威付通省市区开户地联动
  bindRegionPickerColumnChange: function (e) {
    // console.log(e);
    if (e.detail.column != 0) {
      return;
    }
    var index = e.detail.value;
    var pid = this.data.provinceArray[index].areaCode;
    var area = regionData[pid];
    // console.log(pid, index, regionData);
    this.data.regionArray[1] = [];
    for (var i in area) {
      this.data.regionArray[1].push(area[i].areaName);
    }
    this.setData({ regionArray: this.data.regionArray, regionIndex: [index, 0] });
  },
  // 选择银行地址
  bindRegionChange: function (e) {
    var index = e.detail.value;
    var pid = this.data.provinceArray[index[0]].areaCode;
    var provinceName = this.data.provinceArray[index[0]].areaName;
    var cityName = regionData[pid][index[1]].areaName;
    var cityCode = regionData[pid][index[1]].areaCode;
    var bankRegionCode = [pid, cityCode];
    var region = [provinceName, cityName];
    // console.log(region, bankRegionCode);
    this.setData({ bankRegion: region, bankRegionCode: bankRegionCode });
    this.getBankSubbranch();
  },

  bindRegionPickerColumnChange2: function (e) {
    // console.log(e);
    var column = e.detail.column;
    var index = e.detail.value;
    if (column == 2) {
      return;
    }


    if (column == 1) {
      var pid = this.data.province_code;
      var area = regionData[pid];
      this.data.city_code = area[index];
      this.getBankArea(area[index].areaCode, 3);
      return;
    }

    var pid = this.data.provinceArray[index].areaCode;
    this.data.province_code = pid;
    var area = regionData[pid];
    this.data.regionArray2[1] = [];
    for (var i in area) {
      this.data.regionArray2[1].push(area[i].areaName);
    }
    this.setData({ regionArray2: this.data.regionArray2, regionIndex2: [index, 0, 0] });
    this.getBankArea(area[0].areaCode, 3);
  },
  // 选择营业地址
  bindRegionChange2: function (e) {
    var index = e.detail.value;
    var pid = this.data.provinceArray[index[0]].areaCode;
    var provinceName = this.data.provinceArray[index[0]].areaName;
    var cityName = regionData[pid][index[1]].areaName;
    var cityCode = regionData[pid][index[1]].areaCode;
    var countyName = regionData[cityCode][index[2]].areaName;
    var countyCode = regionData[cityCode][index[2]].areaCode;
    var areaRegionCode = [pid, cityCode, countyCode];
    var region = [provinceName, cityName, countyName];
    // console.log(region, bankRegionCode);
    this.setData({ areaRegion: region, areaRegionCode: areaRegionCode });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  uploadimg: function (e) {

    var uploadName = e.currentTarget.dataset.name;
    var detectType = e.currentTarget.dataset.type;
    var that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        if (detectType) {
          that.detectFile(tempFilePaths, detectType);
        }
        if (uploadName){
          that.uploadFile(tempFilePaths, uploadName)
        }
       
      }
    })
  },
  // 网商银行
  uploadFile: function (tempFilePaths, uploadName) {
    var that = this;
    var thisData = that.data.data;
    thisData[uploadName] =  "/image/loader.gif";
    that.setData({
       data: thisData
    })

    wx.uploadFile({
      url: app.data.apiHost + 'apiv2/mch_my_bank/upload', //网商银行地址
      // url:  'http://tenement.com/apiv2/mch_my_bank/upload', //网商银行地址
      filePath: tempFilePaths[0],
      name: 'filedata',
      formData: {
        'name': uploadName
      },
      success(res1) {
        const data = res1.data
        var res = JSON.parse(data);
        if (res.error == 0) {
          // that.setDetectData(res.data);
          thisData[uploadName] = tempFilePaths[0]
          that.data.uploadlist[uploadName] = res['name'];
        } else {
          thisData[uploadName] = "";
          app.alert(res.msg);
        }
        that.setData({
          data: thisData
        })
      }
    })
  },
  detectFile: function (tempFilePaths, detectType) {
    console.log(tempFilePaths);
    var that = this;
    wx.uploadFile({
      url: app.data.apiHost + 'apiv2/qcloud_image/detect', //
      // url: 'http://tenement.com/apiv2/qcloud_image/detect', //仅为示例，非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'type': detectType
      },
      success(res1) {
        const data = res1.data
        var res = JSON.parse(data);
        if (res.code == 200) {
          that.setDetectData(res.data, detectType);
        }
        //do something
      }
    })
  },

  setDetectData: function (detectData, detectType) {
    // console.log(detectData, this.data.detectType);
    var data = this.data.data;
    if (detectType == "idcardDetectA") {
      data.principal = detectData.name;
      data.idCode = detectData.id;
    } else if (detectType == "bizlicense") {
      data.merchantName = detectData['公司名称'];
      data.merchantShortName = detectData['公司名称'];
      data.businessLicense = detectData['注册号'];
      data.address = detectData['地址'];
    } else if (detectType == "bankcard") {
      data.accountCode = detectData['卡号'];
    }
    this.setData({ "data": data });
    console.log(this.data.data);
  },
  setVal: function (e) {
    var name = e.currentTarget.dataset.name;
    var v = e.detail.value;
    var data = this.data.data;
    data[name] = v;
    this.setData({
      data: data
    });
  },

  formSubmit: function (e) {
    var that = this;
    
    
   
    // console.log("this.data",this.data);
    if (this.data.areaRegionCode.length!=3){
       app.alert("请选择商户地址");
       return;
    }
    if (this.data.bankRegionCode.length != 2) {
      app.alert("请选择地址银行地址");
      return;
    }
    that.setData({
      loading: 1,
      disabled: 1
    });
    
    var data = {
      pid: this.data.userInfo.user_id,
      PrincipalPerson: this.data.data.principal,
      PrincipalCertNo: this.data.data.idCode,
      PrincipalMobile: this.data.data.principalMobile,
      AuthCode:"",
      MerchantName: this.data.data.merchantName ? this.data.data.merchantName : this.data.data.merchantShortName,
      Alias: this.data.data.merchantShortName,
      BussAuthNum: this.data.data.businessLicense,
      Mcc: this.data.industryId,
      industryName: this.data.industryName,
      DestinationArea: this.data.areaRegion,
      District: this.data.areaRegionCode[2],
      City: this.data.areaRegionCode[1],
      Province: this.data.areaRegionCode[0],
      county_name: this.data.areaRegion[2],
      city_name: this.data.areaRegion[1],
      province_name: this.data.areaRegion[0],
      Address: this.data.data.address,
      ServicePhoneNo: this.data.data.principalMobile,
      BankCardNo: this.data.data.accountCode,
      BranchId: this.data.bankId,
      bankArea: this.data.bankRegion,
      BranchCity: this.data.bankRegionCode[1],
      BranchProvince: this.data.bankRegionCode[0],
      BranchCityName: this.data.bankRegion[1],
      bankName: this.data.bankName,
      ContactLine: this.data.contactLine,
      ContactLineName: this.data.ContactLineName,
      AccountType: "01",//对私账户 02：对公账户
      FeeValue: this.data.feeValue,
      CertPhotoA: this.data.uploadlist.CertPhotoA,
      CertPhotoB: this.data.uploadlist.CertPhotoB,
      LicensePhoto: this.data.uploadlist.LicensePhoto,
      ShopPhoto: this.data.uploadlist.ShopPhoto,
      ShopEntrancePhoto: this.data.uploadlist.ShopEntrancePhoto,
      MerchantType: "0"+this.data.type,////01:自然人 02:个体工商户 03:企业商户
      Method: "enterNo",
      method :"POST",
      CardHolderAddress: "0",
      BranchName: this.data.bankName,
    };

    app.api("apiv2/mch_my_bank", data, function (res) {
      that.setData({
        loading: 0,
        disabled: 0
      });
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      wx.showModal({
        title: '提交成功',
        showCancel: false,
        content: '系统审核可能需要5分钟左右，请耐心等待',
        success(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: "/pages/mch/index",
            })
          }
        }
      })
     
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getShopInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})